(function(window){
	var

	_tabUtil = window.tabUtil,

	// Get all browser windows
	allWindows = function(callback){
		chrome.windows.getAll({"populate" : true}, function (_allWindows) {
			if(callback){
				callback(_allWindows);
			}
		});
	},

	// Get all browser tabs
	allTabs = function(callback){
		allWindows(function(_allWindows){
			var _allTabs = [];
			for( var i=0; i < all_windows.length; i++) {
				_allTabs = _allTabs.concat(_allWindows[i].tabs);
			}
			if(callback){
				callback(_allTabs);
			}
		});
	},

	// Close the windows that id is in the list "ids"
	closeWindows = function(ids, callback) {
		if(ids != null){
			for( var i=0; i < ids.length; i++) {
				chrome.windows.remove(ids[i], callback);
			}
		}
	}

	//
	closeTabs = function(tabIds, callback){
		if(tabIds != null){
			try{
				if(callback){

					chrome.tabs.remove(tabIds);
				}
				else{
					chrome.tabs.remove(tabIds, callback);
				}
			}catch(ex){
				console.error('Failed to close the tabs' + tabIds, ex);
			}
		}
	};

	// Switch to the tab input
	var switchTab = function(tabId, callback){
		try{
			chrome.tabs.update(parseInt(tabId), {active:true}, function(tab){
				chrome.windows.update(tab.windowId, {focused:true}, callback);
			});
		}catch(ex){
			console.error('Tab does not exist for id ' + tabId, ex);
		}
	}

	var tabUtil = {

		allWindows: allWindows,

		allTabs: allTabs,

		closeWindows: closeWindows,

		closeTabs: closeTabs,

		switchTab: switchTab,

		now: Date.now;
	}

	if(window.tabUtil === tabUtil){
	
		window.tabUtil = _tabUtil;

	}else{

		window.tabUtil = tabUtil;

	}

})(window);
